from hazard_value.shuffle_edges import *
from hazard_value.helpers import *
from hazard_value.nfa import *
from decimal import *
import igraph
import numpy
import sys

# compute the connectivity weight of a network

def compute_hazard_value_baseline (g, D, W, nfa, k, phi, p, sets=set()) :

	edges = set()
	oracle = dict()
	
	for demand in D:
		for s, t in demand: 
			used_edges = compute_nfa_used_edges (g, s, t, nfa, oracle)
			for q in used_edges: edges |= used_edges[q]
	
	if len(edges)==0: return 0, 0.0, 0.0, 1
	coefficients = compute_binomial_coefficients (len(edges))
	probabilities = compute_probabilities(phi, edges, len(edges))

	pending =[frozenset()]
	passed = set()
	weight = Decimal("0.0")
	optimum = Decimal("0.0")
	cummulated_probability = Decimal("0.0")
	scenarios = 0

	# reach^F(s,t)
	while pending :
		f = pending.pop(0)
		passed.add(f)
		cummulated_probability += probabilities[len(f)]
		for demand in D:
			m_opt = 0
			m = 0
			scenarios += 1

			for s, t in demand:
				if W[s, t]>m_opt: 
					m_opt = W[s, t]
				if W[s, t]>m and check_nfa_reach (g, s, t, f, nfa): 
					m = W[s, t]

			optimum += m_opt * probabilities[len(f)]
			weight += m * probabilities[len(f)]

			if m == 0:
				subsets = set(filter(lambda s: s<=f, sets))
				if not subsets:
					sets.add(frozenset(f))

		if len(f) < k:
			for e in edges:
				if e in f : continue
				F = f | {e}
				if not F in passed and not F in pending : 
					pending.append(F)

	optimum = sum([max([W[s, t] for s, t in X]) for X in D])
	optimum *= sum([coefficients[-1][i]*probabilities[i] for i in range(len(edges))])
	return scenarios, weight, optimum, 1-weight/optimum


